# -*- coding:utf-8 -*-

import datetime
from flask import config, current_app, request, jsonify,g
from iHome.utils.response_code import RET
from iHome.models import House,Order
from iHome import db,redis_store
from . import api
from iHome.utils.common import login_required


@api.route('/orders/<order_id>/comment', methods=["PUT"])
@login_required
def comment_order(order_id):
    """
    给订单添加评价
    1. 获取到前端传过来的参数 (comment评论的内容)
    2. 通过id查询到指定的订单
    3. 给该订单设置评价 / 将订单的状态设置成 '完成'
    4. 提交到数据库
    5. 返回结果
    :param order_id:
    :return:
    """

    # 1. 获取到前端传过来的参数
    comment = request.json.get("comment")
    if not comment:
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    # 2. 通过id查询到指定的订单
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_COMMENT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据查询错误")

    if not order:
        return jsonify(errno=RET.NODATA,errmsg="订单不存在")

    # 3. 给该订单设置评价 / 将订单的状态设置成'完成'
    order.comment = comment
    order.status = "COMPLETE"

    # 4. 提交到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存数据失败")

    # 删除指定房屋的redis缓存
    try:
        house_id = order.house_id
        redis_store.delete("house_deatil_%d"% house_id)
    except Exception as e:
        current_app.logger.error(e)

    # 5. 返回结果
    return jsonify(errno=RET.OK,errmsg="OK")


@api.route('/orders/<order_id>/status', methods=["PUT"])
@login_required
def change_order_status(order_id):
    '''
    更改订单的状态:接单,拒单
    1. 取到订单号
    2. 取到订单号所对应的订单模型
    3. 校验该订单的房东是否是登录用户
    4. 修改订单状态:从待接单待评价
    5. 返回
    :param order_id:
    :return:
    '''
    # 取到当前登录用的id
    user_id = g.user_id
    # 取到当前的是接单还是拒单事件
    action = request.json.get("action")
    # 校验参数
    if not action:
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    if action not in ("accept","reject"):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")


    # 订单查询
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_ACCEPT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询订单失败")
    if not order:
        return jsonify(errno=RET.ROLEERR,errmsg="数据错误")

    # # x修改订单状态
    # order.status = "WAIT_COMMENT"
    if "accept" == action:
        # 修改订单状态
        order.status = "WAIT_COMMENT"
    elif "reject" == action:
        order.status = "REJECTED"
        # 获取拒单原因
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR,errmsg="请填写拒单原因")
        # 保存拒单原因
        order.comment = reason

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR,errmsg="保存订单失败")

    return jsonify(errno=RET.OK,errmsg="OK")


@api.route('/user.orders')
@login_required
def get_user_orders():
    '''
    查询当前用户下的所有订单
    1. 获取参数
    :return:
    '''
    # 取到当前用户id
    user_id = g.user_id
    role = request.args.get("role")
    if not role:
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    if role not in ("custom","landlord"):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    try:
        # orders = Order.query.filter(Order.user_id == user_id).all()
        if "custom" == role:
            # 查询房客的订单:从订单列表中查询user_id为当前登录用户的id就可以了
            orders = Order.quert.filter(Order.user_id == user_id).order_by(Order.create_time.desc()).all()
        elif "landlord" == role:
            # 查询房东的订单:要先查询出房东所属的房屋id,再将去订单表中查询指定的房屋id的订单
            houses = House.quert.filter(House.user_id == user_id).all()
            # 获取到自己所有的房屋id
            houses_id = [house.id for house in houses]
            orders = Order.query.filter(Order.house_id.in_(houses_id)).order_by(Order.create_time.desc()).all()
            pass

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询数据失败")

    order_dict = []
    for order in orders:
        order_dict.append(order.to_dict())

    return jsonify(errno=RET.OK,errmsg="OK",data={"orders":order_dict})


@api.route('/orders',methods=["POST"])
@login_required
def add_order():
    """
    1. 获取参数,3个(入住日期,离开日期,房屋的id)
    2. 判断参数是否符合规则
    3. 判断是否存在房屋
    4. 判断该房屋指定时间是否有订单(冲突)
    5. 创建订单模型
    6. 保存订单
    7. 返回结果
    :return:
    """
    # 1. 获取参数,3个(入住日期,离开日期,房屋id)
    data_dict = request.json
    start_date_str = data_dict.get("start_date")
    end_date_str = data_dict.get("end_date")
    house_id = data_dict.get("hid")

    # 2. 判断参数是否符合规则
    if not all([start_date_str,end_date_str,house_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    try:
        start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
        assert start_date < end_date, Exception("开始时间必须小于结束时间")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    # 3. 判断是否存在该房屋
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询数据错误")

    if not house:
        return jsonify(errno=RET.NODATA,errmsg="该房屋不存在")

    # 4.判断该房屋指定时间是否有订单冲突
    try:
        filters = [Order.house_id == house_id, Order.begin_date < end_date, Order.end_date > start_date]
        # 查询冲突订单的数据
        order_count = Order.query.filter(*filters).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询数据错误")
    # 如果冲突订单的数量大于0
    if order_count > 0:
        # 已经存在相同时间冲突的订单
        return jsonify(errno=RET.DATAERR,errmsg="当前房屋已经被预定")
    # 5. 创建订单模型
    days = (end_date - start_date).days
    order = Order()
    order.house_id = g.house_id
    order_begin_date = start_date
    order_end_date = end_date
    order.days = days
    order.house_price = house.price
    order.amount = house.price * days

    # 房屋的订单数据加1
    house.order_count += 1
    # 6. 保存到数据库
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="保存数据失败")




































